//
//  RESTClient.m
//  iFlick
//
//  Created by 张 霄鹤 on 09-10-31.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "RESTClient.h"

#import "MD5.h"

#import "Reachability.h"


@implementation RESTClient

@synthesize delegate = _delegate;

- (id)initWithAPIURL:(NSString *)url withSecret:(NSString *)sec{
	if(self = [super init]){
		serverAPI = url;
		secretKey = sec;
	}
	return self;
}


- (id)request:(NSString *)method withParameters:(NSDictionary *)params{
	if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
		return nil;
	}
	NSMutableDictionary *mds = [NSMutableDictionary dictionaryWithDictionary:params];
	// TODO 请求REST方式，并且返回获取的数据
	NSString *sig = [self genApiSig:method params:mds];
	[mds setObject:sig forKey:@"api_sig"];
	NSInteger ps = [mds count];
	NSMutableString *ret = nil;
	ret = [NSMutableString string];
	[ret appendString:serverAPI];
	[ret appendFormat:@"?method=%@",method];
	if(ps > 0){
		[ret appendString:@"&"];
		NSString *key;
		NSString *value;
		NSArray * keys = [[mds keyEnumerator] allObjects];
		// 此方法会创建一个新的NSArray，但是不会拷贝原有数组的元素，只是包含引用
		NSArray *ka = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
		int i = 0;
		for(;i<ps - 1;i++){
			key = [ka objectAtIndex:i];
			value = [mds objectForKey:key];
			[ret appendFormat:@"%@=%@&",[key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
		}
		i = ps - 1;
		if(i > 0){
			key = [ka objectAtIndex:i];
			value = [mds objectForKey:key];
			[ret appendFormat:@"%@=%@",[key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
		}
	}
	NSURL *url = [NSURL URLWithString:ret];
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	[request setTimeoutInterval:120];
	[request setHTTPMethod:@"GET"];
	NSString *version  = [[[NSBundle mainBundle] infoDictionary] valueForKey:[NSString stringWithFormat:@"CFBundleVersion"]];
	[request addValue:[NSString stringWithFormat:@"iFlick/%@",version] forHTTPHeaderField:@"User-Agent"];
	[request addValue:@"gzip" forHTTPHeaderField: @"Accept-Encoding"];
	NSURLResponse *resp = nil;
	NSError *err = nil;
	NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
	if(err){
		return err;
	}
	if(data){
		NSString *xml = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
		return xml;
	}
	return nil;
}

//- (NSArray *)getSortedKeys:(NSDictionary *)params{
//	NSArray * keys = [[params keyEnumerator] allObjects];
//	// 此方法会创建一个新的NSArray，但是不会拷贝原有数组的元素，只是包含引用
//	NSArray *akeys = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
//	return akeys;
//}

- (NSString *)genApiSig:(NSString *)method params:(NSDictionary *)paramDict{
	NSMutableString *ret = [NSMutableString stringWithString:secretKey];
	
	NSMutableDictionary *ps = [NSMutableDictionary dictionaryWithDictionary:paramDict];
	[ps setObject:method forKey:@"method"];
	
	// [paramDict setValue:apiKey forKey:@"api_key"];	
	NSArray * keys = [[ps keyEnumerator] allObjects];
	// 此方法会创建一个新的NSArray，但是不会拷贝原有数组的元素，只是包含引用
	NSArray *akeys = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	
	
	for(id key in akeys){
		[ret appendFormat:@"%@%@",key,[ps objectForKey:key]];
	}
	// 注意，keys akeys 这两个不是在这个方法中创建的，就不需要release了
	
	const char *us = [ret UTF8String];
	
	
	int len = strlen(us);
	MD5 m = MD5WithBytes(us,len);
	NSString * sret = MD5ToString(&m);
	return sret;
}


// NSURLConnection Delegate
/**
 * 连接出错的情况
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	if(_delegate){
		[_delegate didFail:error];
	}
}

/**
 * 接受数据完毕
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	if(_delegate){
		[_delegate didFinishLoad:data];
	}
}

/**
 * 接受响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

}

/**
 * 数据发送部分
 */
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten
 totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{

}

/**
 * 数据装载完毕
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

}

@end
